//
//  BookingInformationViewController.m
//  TravelFollowYourHeart
//
//  Created by ENERGY on 2017/12/25.
//  Copyright © 2017年 Lwx. All rights reserved.
//

#import "BookingInformationViewController.h"
#import "TopUpView.h"
#define border 10
#define labelH 20
#define surePayBtnH 50

@interface BookingInformationViewController ()
@property (nonatomic, strong)UILabel * titleLab;
@property (nonatomic, strong)UILabel * priceLab;
@property (nonatomic, strong)UILabel * orderMoneyLab;
@property (nonatomic, strong)UIButton * surePayBtn;
@property (nonatomic, strong)NSString * orderListStr;//订单号
@property (nonatomic, strong)TopUpView * topUpView;//支付弹页
- (void)weiXinpay:(NSDictionary *)dic;
- (void)payByALiWithHandle:(NSString *)orderString;
@end

@implementation BookingInformationViewController(networking)
//订单预览信息
- (void)getActivityDetail{
    NSDictionary * dic = @{
                           @"type":self.type,
                           @"tid":self.tid,
                           @"mid":[UserModel intance].member_id,
                           @"token":[UserModel intance].token,
                           @"pid":self.activityId
                           };
//    WS(ws)
    [self showprogressHUD];
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/member/addOrder") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        [self hiddenProgressHUD];
        if (error) {
            [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
            self.surePayBtn.userInteractionEnabled = NO;
        }else{
            if ([obj[@"code"] integerValue] == 100000){
                self.surePayBtn.userInteractionEnabled = YES;
                NSDictionary * dic = obj[@"data"];
                self.orderListStr = dic[@"number"];
                self.titleLab.text = [NSString stringWithFormat:@"订单号 ： %@", dic[@"number"]];
            }else{
                [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
                if ([obj[@"msg"] isEqualToString:@"您的账号已在其他设备上登录"]) {
                    self.surePayBtn.userInteractionEnabled = NO;
                }
                self.surePayBtn.userInteractionEnabled = NO;
            }
        }
    }];
}

//微信支付
- (void)getWeChatPayOrderPay{
    NSDictionary * dic = @{
                           @"total_amount":self.reservationDeposit,
//                           @"total_amount":@"0.01",
                           @"order":self.orderListStr
                           };
    [self showprogressHUD];
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/member/wxpay") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        [self hiddenProgressHUD];
        if (error) {
            [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
        }else{
            [self weiXinpay:obj[@"data"]];
            [self paySuccessListNumBack];
        }
    }];
}
//阿里支付
- (void)getAliPayOrderPay{
    NSDictionary * dic = @{
                           @"total_amount":self.reservationDeposit,
                           @"order":self.orderListStr
                           };
    [self showprogressHUD];
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/member/alipay") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        [self hiddenProgressHUD];
        if (error) {
            [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
        }else{
            [self payByALiWithHandle:obj[@"data"]];
            [self paySuccessListNumBack];
        }
    }];
}

//给后台回传订单号
- (void)paySuccessListNumBack{
    NSDictionary * dic = @{
                           @"order":self.orderListStr
                           };
    [self showprogressHUD];
    [[HttpRequest shardWebUtil] postNetworkRequestURLString:Url(@"/member/pay_success") andParas:dic andTransferGottenData:^(id obj, NSError *error) {
        [self hiddenProgressHUD];
        if (error) {
            [[HUDHelper sharedInstance] tipMessage:obj[@"msg"]];
        }else{
//            [self payByALiWithHandle:obj[@"data"]];
        }
    }];
}
@end
@implementation BookingInformationViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"预定信息";
    self.view.backgroundColor = getColor(bgColor);
    [self getActivityDetail];//网络接口
    [self.view addSubview:self.titleLab];
    [self.view addSubview:self.priceLab];
    [self.view addSubview:self.orderMoneyLab];
    [self.view addSubview:self.surePayBtn];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess:) name:@"支付成功success" object:nil];
}

- (UILabel *)titleLab{
    if (!_titleLab) {
        int titleLabW = SCREEN_WIDTH - 2 * border;
        _titleLab = [[UILabel alloc] init];
        _titleLab.frame = CGRectMake(border, border, titleLabW, labelH);
        _titleLab.font = [UIFont systemFontOfSize:14.0];
        _titleLab.text = @"01.XXXXXXXXXXXXX";
        _titleLab.textColor = [UIColor blackColor];
    }return _titleLab;
}

- (UILabel *)priceLab{
    if (!_priceLab) {
        _priceLab = [[UILabel alloc] init];
        _priceLab.frame = CGRectMake(self.titleLab.left, self.titleLab.bottom + 5, self.titleLab.width, labelH);
        _priceLab.font = [UIFont systemFontOfSize:14.0];
//        _priceLab.text = @"￥500";
        _priceLab.text = [NSString stringWithFormat:@"￥%@", self.totalMoney];
        _priceLab.textColor = [UIColor redColor];
    }return _priceLab;
}

- (UILabel *)orderMoneyLab{
    if (!_orderMoneyLab) {
        _orderMoneyLab = [[UILabel alloc] init];
        _orderMoneyLab.frame = CGRectMake(self.priceLab.left, self.priceLab.bottom + 2* border, self.priceLab.width, labelH);
        _orderMoneyLab.font = [UIFont systemFontOfSize:14.0];
        _orderMoneyLab.text = [NSString stringWithFormat:@"预定金额    ￥%@", self.reservationDeposit];
        _orderMoneyLab.textColor = [UIColor redColor];
    }return _orderMoneyLab;
}

- (UIButton *)surePayBtn{
    if (!_surePayBtn) {
        _surePayBtn = [[UIButton alloc] init];
        _surePayBtn.frame = CGRectMake(0, SCREEN_HEIGHT - surePayBtnH - 64, SCREEN_WIDTH, surePayBtnH);
        [_surePayBtn setBackgroundColor:getColor(@"ffbb02")];
        [_surePayBtn setTitle:@"确认支付" forState:UIControlStateNormal];
        [_surePayBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _surePayBtn.titleLabel.font = DEF_FontSize_16;
        [_surePayBtn addTarget:self action:@selector(surePayBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }return _surePayBtn;
}

- (void)surePayBtnClick{
    __weak typeof (self)weakSelf = self;
    self.topUpView = [[TopUpView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.topUpView.weChatBtnClick = ^{
        NSLog(@"微信支付");
        [weakSelf getWeChatPayOrderPay];
    };
    self.topUpView.aliPayBtnClick = ^{
        NSLog(@"支付宝");
//        [weakSelf getOrderPay];
        [weakSelf getAliPayOrderPay];
    };
    [self.topUpView show];
}

/**
 微信支付
 */
- (void)weiXinpay:(NSDictionary *)dic{
    PayReq *request = [[PayReq alloc]init];
    request.partnerId = dic[@"partnerid"];
    request.timeStamp = [dic[@"timestamp"] intValue];
    request.sign = dic[@"sign"];
    request.prepayId = dic[@"prepay_id"];
    request.nonceStr = dic[@"nonce_str"];
    request.package = @"Sign=WXPay";
    
    [WXApi sendReq:request];
}

/**
 支付宝支付

 @param orderString orderString description
 参数：orderString 后台返回签名加密的 字符串
 */
- (void)payByALiWithHandle:(NSString *)orderString{
    //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
    NSString *appScheme = @"ShangCaiLeTravelFollowYourHeart";
    // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        if ([resultDic[@"resultStatus"] isEqualToString:@"6001"]) {
            ShowMessage(@"支付失败");
        }
        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            [self.view makeToast:@"支付成功!" duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
//                [self getUserById];
                [self.topUpView hidden];
                [self.navigationController popViewControllerAnimated:YES];

//                //返回到指定的控制器，要保证前面有入栈。
//                int index = (int)[[self.navigationController viewControllers]indexOfObject:self];
//                if (index>2) {
//                    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:(index-2)] animated:YES];
//                }else
//                {
//                    [self.navigationController popToRootViewControllerAnimated:YES];
//                }
            }];
        }
    }];
}

- (void)paySuccess:(NSNotification *)notification{
    NSLog(@"成功");
    [self.topUpView hidden];
//    NSDictionary * dic = notification.userInfo;//取出notification内容
    [self.navigationController popViewControllerAnimated:YES];

}

@end
